package com.blrs.service.demand.impl;

import java.util.*;

import com.blrs.common.constant.RouteIndex;
import com.blrs.common.core.domain.entity.SysDept;
import com.blrs.common.utils.ReflectionUtils;
import com.blrs.common.utils.SecurityUtils;
import com.blrs.common.utils.StringUtils;
import com.blrs.common.utils.uuid.UUID;
import com.blrs.domain.ActivityReception;
import com.blrs.domain.BusinessOpportunityInformation;
import com.blrs.domain.DemandReception;
import com.blrs.mapper.*;
import com.blrs.service.demand.IDemandReleaseService;
import com.blrs.service.indexInfo.IInfoIndexService;
import com.blrs.system.mapper.SysDeptMapper;
import com.blrs.system.mapper.SysUploadFileMapper;
import com.blrs.system.service.ISysDeptService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.blrs.domain.DemandRelease;
import org.springframework.transaction.annotation.Transactional;

/**
 * 需求发布Service业务层处理
 * 
 * @author yang
 * @date 2024-01-26
 */
@Service
public class DemandReleaseServiceImpl implements IDemandReleaseService
{
    @Autowired
    private DemandReleaseMapper demandReleaseMapper;
    @Autowired
    private SysDeptMapper sysDeptMapper;
    @Autowired
    private SysUploadFileMapper sysUploadFileMapper;
    @Autowired
    private EnterpriseInfoMapper enterpriseInfoMapper;
    @Autowired
    private DemandReceptionMapper demandReceptionMapper;
    @Autowired
    private SysAreaMapper areaMapper;
    @Autowired
    private ISysDeptService sysDeptService;
    @Autowired
    private IInfoIndexService infoIndexService;
    @Autowired
    private BusinessOpportunityInformationMapper businessOpportunityInformationMapper;

    /**
     * 查询需求发布
     * 
     * @param projectId 需求发布主键
     * @return 需求发布
     */
    @Override
    public DemandRelease selectDemandReleaseByProjectId(String projectId)
    {
        return demandReleaseMapper.selectDemandReleaseByProjectId(projectId);
    }

    /**
     * 查询需求发布列表
     * 
     * @param demandRelease 需求发布
     * @return 需求发布
     */
    @Override
    public List<DemandRelease> selectDemandReleaseList(DemandRelease demandRelease)
    {
        if (!SecurityUtils.getOrgId().equals(100L)){
            //说明是平台端的用户，可以进行审核
            demandRelease.setBelongTo(SecurityUtils.getOrgId());
        }
        List<DemandRelease> demandReleases = demandReleaseMapper.selectDemandReleaseList(demandRelease);
        for (DemandRelease release : demandReleases) {
           if(Objects.nonNull(release.getProjectLocation())){
               release.setProjectLocation(areaMapper.selectSysAreaByAreaId(release.getProjectLocation()).getAreaName());
           }
            release.setUrl( sysUploadFileMapper.selectUrlByCode("demand",release.getUploadFile()));

        }
        return demandReleases;
    }

    @Override
    public List<DemandRelease> selectDemandReleaseListByReception(DemandRelease demandRelease) {
        List<DemandRelease> demandReleases =demandReleaseMapper.selectDemandReleaseByReceptionList(demandRelease);
        for (DemandRelease release : demandReleases) {
           // release.setProjectLocation(areaMapper.selectSysAreaByAreaId(release.getProjectLocation()).getAreaName());
            release.setUrl( sysUploadFileMapper.selectUrlByCode("demand",release.getUploadFile()));
            release.setBidding(demandReceptionMapper.selectBiddingByProjectIdAndReceiverId(release.getProjectId(), SecurityUtils.getOrgId()));
            BusinessOpportunityInformation businessOpportunityInformation = businessOpportunityInformationMapper.selectAllByProjectId(release.getProjectId());
            if (businessOpportunityInformation!= null){
                //说明成功转成商机了，获取商机的阶段
                release.setIsBusiness("是");
                release.setBusinessState(businessOpportunityInformation.getBusinessState());
            }else {
                release.setIsBusiness("否");
            }
        }
        return demandReleases;
    }

    @Override
    public int bid(String projectId) {
      return   demandReleaseMapper.BiddingDemand(projectId,SecurityUtils.getOrgId(),SecurityUtils.getOrgName());
    }

    @Override
    public List<DemandReception> selectBidder(String projectId) {
        List<DemandReception> demandReceptions = demandReceptionMapper.seeBidder(projectId);

        return demandReceptions;
    }

    @Override
    public int close(String projectId) {
       return demandReleaseMapper.closeProductRelease(projectId);
    }


    @Override
    public List<DemandRelease> selectDemandReleaseListByAudit(DemandRelease demandRelease) {
        if (SecurityUtils.getOrgId().equals(100L)){
            List<DemandRelease> demandReleases = demandReleaseMapper.selectDemandReleaseList(demandRelease);
            for (DemandRelease release : demandReleases) {
                //release.setProjectLocation(areaMapper.selectSysAreaByAreaId(release.getProjectLocation()).getAreaName());
                release.setUrl( sysUploadFileMapper.selectUrlByCode("demand",release.getUploadFile()));
            }
            return demandReleases;
        }else {
            return Collections.emptyList();
        }
    }



    /**
     * 新增需求发布
     * 
     * @param demandRelease 需求发布
     * @return 结果
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public int insertDemandRelease(DemandRelease demandRelease) throws NoSuchFieldException, IllegalAccessException {
        demandRelease.setProjectId(UUID.randomUUID().toString().replaceAll("-", ""));
            //获取所有的入驻企业id
        // 获取所有的入驻企业id
    if (demandRelease.getSendType().equals("groupSend")){
        for (String s : demandRelease.getEnterpriseId()) {
            if (StringUtils.isNotEmpty(s)){
                //先查询对应组织机构id
                DemandReception demandReception = new DemandReception();
                //根据企业id查询企业名称
                String enterpriseName = enterpriseInfoMapper.selectEnterpriseInfoByEnterpriseId(s).getEnterpriseName();
                //根据企业名称查询组织机构id
                demandReception.setReceiverId(sysDeptMapper.selectByDeptName(enterpriseName).getDeptId());
                demandReception.setEnterpriseId(s);
                demandReception.setProjectId(demandRelease.getProjectId());
                demandReceptionMapper.insertDemandReception(demandReception);

            }
        }
    }else {
        //一键发送
        List<SysDept> deptList = sysDeptMapper.selectOrgList(null);
        if (deptList != null && !deptList.isEmpty()) {
            List<DemandReception> demandReceptions = new ArrayList<>();
            for (SysDept sysDept : deptList) {
                DemandReception demandReception = new DemandReception();
                demandReception.setProjectId(demandRelease.getProjectId());
                demandReception.setReceiverId(sysDept.getDeptId());
                demandReceptions.add(demandReception);
            }
            // 批量插入
            demandReceptionMapper.batchInsertDemandReception(demandReceptions);
        }
    }
        //状态
        demandRelease.setStatus("审核");
        demandRelease.setSendUnit(SecurityUtils.getOrgName());
        demandRelease.setCreationName(SecurityUtils.getUsername());
        ReflectionUtils.setCommonPrivateProperty(demandRelease);
        demandRelease.setBelongTo(SecurityUtils.getOrgId());
        demandRelease.setOrganizationName(SecurityUtils.getOrgName());
        return demandReleaseMapper.insertDemandRelease(demandRelease);
    }

    /**
     * 修改需求发布
     * 
     * @param demandRelease 需求发布
     * @return 结果
     */
    @Override
    public int updateDemandRelease(DemandRelease demandRelease)
    {
        return demandReleaseMapper.updateDemandRelease(demandRelease);
    }

    /**
     * 批量删除需求发布
     * 
     * @param projectIds 需要删除的需求发布主键
     * @return 结果
     */
    @Override
    public int deleteDemandReleaseByProjectIds(String[] projectIds)
    {
        return demandReleaseMapper.deleteDemandReleaseByProjectIds(projectIds);
    }

    /**
     * 删除需求发布信息
     * 
     * @param projectId 需求发布主键
     * @return 结果
     */
    @Override
    public int deleteDemandReleaseByProjectId(String projectId)
    {
        return demandReleaseMapper.deleteDemandReleaseByProjectId(projectId);
    }

    @Override
    public int terminationPolicy(DemandRelease demandRelease) {
        demandReceptionMapper.deleteDemandReceptionByProjectId(demandRelease.getProjectId());
        return demandReleaseMapper.updateProductReleaseByEnd(demandRelease);
    }

    @Override
    public int updateStatus(DemandRelease demandRelease) {
       if (demandRelease.getSendType().equals("oneClick")){
           infoIndexService.createAndInsertInfoIndex(
                   demandRelease.getProjectId(),
                   demandRelease.getProjectName(),
                   demandRelease.getOrganizationName(),
                   demandRelease.getBelongTo(),
                   "需求信息",
                   RouteIndex.DEMAND_ROUTE,
                   2125L,
                   demandRelease.getSendType()
           );
       }
        return demandReleaseMapper.updateDemandReleaseStatus(demandRelease.getProjectId());
    }


}
